package at.codebase.web.servlets.admin;

import static at.codebase.web.util.i18n.I18NFactory.i18n;

import java.util.ArrayList;

import at.codebase.core.PageLinkFactory;
import at.codebase.core.ServletList;
import at.codebase.core.log.Log;
import at.codebase.core.log.LogTypes;
import at.codebase.db.entities.ELogMessage;
import at.codebase.security.SecureStringBuilder;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;
import at.codebase.web.util.URLParameters.ParameterParsingException;
import at.codebase.web.util.i10n.L10N;
import at.codebase.web.util.servlet.SecureServlet;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

/**
 * Displays logs to the administrators of the application.
 * 
 * @author Daniel Marth <danielmarth@gmx.at>
 */
public class LogViewer extends SecureServlet {

	private final int LogMessagesPerPage = 20;

	@Override
	protected RequestType requestType() {
		return RequestType.POST_AND_GET;
	}
	
	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ADMIN);
	}

	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		int filter = 0;
		long userId = -1;
		try {
			filter = requestInfo.getParameters().getInteger("logType");
			userId = requestInfo.getParameters().getLong("logUserId");
		} catch (ParameterDoesNotExistException e1) { } 
		catch (ParameterParsingException e1) { }
		
		int page;
		try {
			page = requestInfo.getParameters().getInteger("page");
			if (page < 1) {
				page = 1;
			}
		} catch (ParameterDoesNotExistException e) {
			page = 1;
		} catch (ParameterParsingException e) {
			page = 1;
		}
		int lastPage = (int) Math
				.ceil((double) Log.getLogMessageCountByType(filter, userId)
						/ (double) LogMessagesPerPage);
		if (lastPage == 0) {
			lastPage = 1;
		}
		if (page > lastPage) {
			page = lastPage;
		}
		if (requestType.equals(RequestType.POST)) {
			redirectTo("/admin/logViewer?logType=" + filter
					+ (userId > 0 ? "&logUserId=" + userId : ""));
		}
		
		MainTemplate mainTemplate = new MainTemplate(requestInfo, writer());
		mainTemplate.setTitle("Admin Logs");
		Template logTemplate = TemplateEngine.getTemplate("log/log_layout.html");
		logTemplate.setTemplate("adminMenuBar", TemplateEngine.getTemplate("admin/admin_menu_bar.html"));
		
		if(userId > 0){
			logTemplate.setText("logUserId", String.valueOf(userId));
		}
		
		for (int i = LogTypes.FIRST; i < LogTypes.LAST; i++) {
			if (filter == i) {
				logTemplate.setText(
						new SecureStringBuilder().appendInsecure("selected")
								.appendInsecure(String.valueOf(i)).toString(),
						"selected=\"selected\"");
			} else {
				logTemplate.setText(
						new SecureStringBuilder().appendInsecure("selected")
								.appendInsecure(String.valueOf(i)).toString(),
						"");
			}
		}
		ArrayList<Template> rows = new ArrayList<Template>();
		for (ELogMessage logEntry : Log.getLogMessages(filter, userId, (page - 1)
				* LogMessagesPerPage, LogMessagesPerPage)) {
			Template logEntryTemplate = TemplateEngine
					.getTemplate("log/log_entry.html");
			logEntryTemplate.setText("logType",
					String.valueOf(logEntry.getType()));
			logEntryTemplate.setText("logDate", String.valueOf(L10N.formatDate(
					requestInfo.getLocale(), logEntry.getTimestamp())));
			logEntryTemplate.setText("logTime", String.valueOf(L10N.formatTimeExact(
					requestInfo.getLocale(), logEntry.getTimestamp())));
			if(logEntry.getUser() != null){
				logEntryTemplate.setText("logUser", String.valueOf(logEntry.getUser().getId()));
			}else{
				logEntryTemplate.setText("logUser","null");
			}
			logEntryTemplate.setHTML("logMessage",
					Log.parseLogMessage(logEntry));
			rows.add(logEntryTemplate);
		}
		logTemplate.setText("date", i18n(requestInfo.getLocale())
				.string("date"));
		logTemplate.setText("time", i18n(requestInfo.getLocale())
				.string("time"));
		logTemplate.setText("message",
				i18n(requestInfo.getLocale()).string("message"));
		logTemplate.setTemplates("logEntries", rows);
		logTemplate.setHTML("pageLinks", PageLinkFactory.createLinks(
				ServletList.LogvViewerWithPage + "&logType=" + filter
						+ (userId > 0 ? "&logUserId=" + userId : ""), page,
				lastPage));
		mainTemplate.setTemplate("body", logTemplate);
		mainTemplate.render(requestInfo.getLocale());
	}
}
